package com.dailyblue.java.reflection;

import lombok.SneakyThrows;

import java.lang.reflect.Field;

public class DemoC {
    @SneakyThrows
    public static void main(String[] args) {
        Class c = Class.forName("com.dailyblue.java.reflection.Student");
        Object obj = c.getDeclaredConstructor().newInstance();
        // 获取所有属性
        // 获取所有定义的属性
        Field[] fields1 = c.getDeclaredFields();
        // 获取所有拥有的public属性(包含继承下来的)
        Field[] fields2 = c.getFields();
        for (Field f : fields1) {
            System.out.println(f);
        }
        System.out.println("---------------------------------------");
        for (Field f : fields2) {
            System.out.println(f);
        }
        System.out.println("---------------------------------------");
        // 在所定义的属性中查找指定名称的属性
        //  Field f1 = c.getDeclaredField("id"); ❌
        Field f2 = c.getDeclaredField("no");
        Field f3 = c.getDeclaredField("schoolName");
        // 在所拥有的public属性中查找指定名称的属性
        Field f4 = c.getField("name");
        // System.out.println(f1);
        System.out.println(f2);
        System.out.println(f3);
        System.out.println(f4);
        System.out.println("---------------------------------------");
        // 给属性赋值
        f2.setAccessible(true); // 设置私有属性可以访问
        f2.set(obj,1);
        f3.set(obj,"商洛学院");
        System.out.println(obj);
        System.out.println("---------------------------------------");
        // 获取属性的值
        Object v1 = f2.get(obj);
        Object v2 = f3.get(obj);
        System.out.println(v1);
        System.out.println(v2);

    }
}
